package com.example.reward.filter;

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMinMax implements InputFilter {
    private final int min;
    private final int max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        try {
            String newVal = dest.subSequence(0, dstart)
                    + source.toString()
                    + dest.subSequence(dend, dest.length());
            int input = Integer.parseInt(newVal);
            if (isInRange(min, max, input)) return null;
        } catch (NumberFormatException ignored) {
        }
        return "";
    }

    private boolean isInRange(int min, int max, int value) {
        return value >= min && value <= max;
    }
}
